import service, { request } from '@/utils/request'

// API基础配置
const API_CONFIG = {
  // 用户相关
  USER: {
    LOGIN: '/api/scenic/v1/login',
    LOGOUT: '/api/scenic/v1/login',
    REFRESH_TOKEN: '/auth/refresh',
    USER_INFO: '/user/info',
    UPDATE_PROFILE: '/user/profile'
  },
  
  // 标注相关
  ANNOTATION: {
    LIST: '/api/manage/gj/v1/culturalMap/page',
    CREATE: '/api/manage/gj/v1/culturalMap/add',
    UPDATE: '/api/manage/gj/v1/culturalMap/edit',
    DELETE: '/api/manage/gj/v1/culturalMap',
    DETAIL: '/api/manage/gj/v1/culturalMap'
  },
  
  // 文件相关
  FILE: {
    UPLOAD: '/api/cultural/gj/v1/common/upload',
    DOWNLOAD: '/file/download',
    DELETE: '/file/delete'
  }
}

// 用户相关API
export const userApi = {
  // 登录
  login(data) {
    return request.post(API_CONFIG.USER.LOGIN, data, {
      showSuccessMsg: true,
      loadingText: '登录中...'
    })
  },

  // 登出
  logout() {
    return request.post(API_CONFIG.USER.LOGOUT, {}, {
      showSuccessMsg: true
    })
  },

  // 刷新token
  refreshToken(refreshToken) {
    return request.post(API_CONFIG.USER.REFRESH_TOKEN, {
      refreshToken
    }, {
      loading: false // 刷新token时不显示loading
    })
  },

  // 获取用户信息
  getUserInfo() {
    return request.get(API_CONFIG.USER.USER_INFO, {}, {
      loading: false
    })
  },

  // 更新用户资料
  updateProfile(data) {
    return request.put(API_CONFIG.USER.UPDATE_PROFILE, data, {
      showSuccessMsg: true,
      loadingText: '更新中...'
    })
  }
}

// 标注相关API
export const annotationApi = {
  // 获取标注列表
  getList(data) {
    return service({
      url: `${API_CONFIG.ANNOTATION.LIST}/${data.pageNum}/${data.pageSize}`,
      method: 'post',
      data,
      loading: false
    })
  },

  // 创建标注
  create(data) {
    return request.post(API_CONFIG.ANNOTATION.CREATE, data, {
      showSuccessMsg: true,
      loadingText: '创建中...'
    })
  },

  // 更新标注
  update(data) {
    // return request.put(`${API_CONFIG.ANNOTATION.UPDATE}/${id}`, data, {
    //   showSuccessMsg: true,
    //   loadingText: '更新中...'
    // })
    return request.post(API_CONFIG.ANNOTATION.UPDATE, data, {
      showSuccessMsg: true,
      loadingText: '更新中...'
    })
  },

  // 删除标注
  delete(id) {
    return request.delete(`${API_CONFIG.ANNOTATION.DELETE}/${id}`, {}, {
      showSuccessMsg: true,
      loadingText: '删除中...'
    })
  },

  // 获取标注详情
  getDetail(id) {
    return request.get(`${API_CONFIG.ANNOTATION.DETAIL}/${id}`)
  },

  // 批量删除
  batchDelete(ids) {
    return request.post(`${API_CONFIG.ANNOTATION.DELETE}/batch`, {
      ids
    }, {
      showSuccessMsg: true,
      loadingText: '删除中...'
    })
  }
}

// 文件相关API
export const fileApi = {
  // 上传文件
  upload(file, onProgress) {
    const formData = new FormData()
    formData.append('file', file)
    
    return request.upload(API_CONFIG.FILE.UPLOAD, formData, {
      loadingText: '上传中...',
      onUploadProgress: onProgress
    })
  },

  // 上传多个文件
  uploadMultiple(files, onProgress) {
    const formData = new FormData()
    files.forEach(file => {
      formData.append('files', file)
    })
    
    return request.upload(API_CONFIG.FILE.UPLOAD + '/multiple', formData, {
      loadingText: '上传中...',
      onUploadProgress: onProgress
    })
  },

  // 下载文件
  download(fileId, fileName) {
    return request.download(`${API_CONFIG.FILE.DOWNLOAD}/${fileId}`, {}, {
      loadingText: '下载中...'
    }).then(response => {
      // 处理文件下载
      const blob = new Blob([response.data])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = fileName || 'download'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    })
  },

  // 删除文件
  delete(fileId) {
    return request.delete(`${API_CONFIG.FILE.DELETE}/${fileId}`, {}, {
      showSuccessMsg: true
    })
  }
}

// 通用API工具
export const commonApi = {
  // 健康检查
  healthCheck() {
    return request.get('/health', {}, {
      loading: false,
      showErrorMsg: false
    })
  },

  // 获取系统配置
  getSystemConfig() {
    return request.get('/system/config', {}, {
      loading: false
    })
  },

  // 发送验证码
  sendVerifyCode(phone) {
    return request.post('/common/verify-code', {
      phone
    }, {
      showSuccessMsg: true,
      loadingText: '发送中...'
    })
  },
  // 保存或修改配置
  saveConfig(data) {
    return request.post('/api/manage/v1/configManage',data, {
      showSuccessMsg: true,
      loadingText: '保存配置中...'
    })
  },
  // 获取底图配置
  getConfig(businessCode) {
    return request.get(`/api/manage/v1/configManage/backgroundImage/${businessCode}`,{}, {
      loading: true
    })
  },
}

// 导出所有API
export default {
  user: userApi,
  annotation: annotationApi,
  file: fileApi,
  common: commonApi
}

// 导出API配置，供其他地方使用
export { API_CONFIG }

/**
 * API使用示例
 *
 * 1. 基础使用：
 * import api from '@/api'
 *
 * // 登录
 * const loginResult = await api.user.login({
 *   username: 'admin',
 *   password: '123456'
 * })
 *
 * // 获取标注列表
 * const annotations = await api.annotation.getList({
 *   page: 1,
 *   pageSize: 10
 * })
 *
 * 2. 自定义配置：
 * import { request } from '@/utils/request'
 *
 * // 不显示loading
 * const result = await request.get('/api/data', {}, {
 *   loading: false
 * })
 *
 * // 不显示错误消息
 * const result = await request.post('/api/data', data, {
 *   showErrorMsg: false
 * })
 *
 * // 显示成功消息
 * const result = await request.post('/api/data', data, {
 *   showSuccessMsg: true
 * })
 *
 * 3. 高级用法：
 * import http from '@/utils/http'
 *
 * // 重试请求
 * const result = await http.retry(() => api.user.getUserInfo(), {
 *   maxRetries: 3,
 *   delay: 1000
 * })
 *
 * // 并发请求
 * const results = await http.concurrent([
 *   api.user.getUserInfo(),
 *   api.annotation.getList()
 * ])
 *
 * // 确认请求
 * const result = await http.confirmRequest(
 *   () => api.annotation.delete(id),
 *   {
 *     title: '删除确认',
 *     message: '确定要删除这个标注吗？'
 *   }
 * )
 */
